package com.imageim.yimirror.ui.fragment;

import android.text.TextUtils;
import android.view.View;

import com.imageim.yimirror.R;
import com.imageim.yimirror.base.BaseFragment;
import com.imageim.yimirror.base.Constants;
import com.imageim.yimirror.bean.RadarResultBean;
import com.imageim.yimirror.bean.RadarTitleBean;
import com.imageim.yimirror.common.network.constants.NetConstants;
import com.imageim.yimirror.common.ui.RadarView5New;
import com.imageim.yimirror.common.ui.RadarViewNew;
import com.imageim.yimirror.common.ui.SpreadView;
import com.imageim.yimirror.common.util.UserUtil;
import com.imageim.yimirror.net.NetPresenterImpl;
import com.imageim.yimirror.net.NetView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

import butterknife.BindView;

/**
 * Created by Yuaihen.
 * on 2018/11/29
 * 雷达图Fragment
 */
public class RadarFragment extends BaseFragment implements NetView {

    @BindView(R.id.spreadTV)
    SpreadView mSpreadTV;
    @BindView(R.id.radar_view_woman)
    RadarViewNew mRadarViewWoman;
    @BindView(R.id.radar_view_man)
    RadarView5New mRadarViewMan;
    private NetPresenterImpl mNetPresenter;
    private float[] mOptimizedStyleScores;
    private RadarResultBean mRadarResultBean;
    private List<RadarTitleBean.ListBean> mTitleList;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_radar;
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {
        mNetPresenter = new NetPresenterImpl(this);
        getRadarTitleDesc();
    }


    /**
     * 获取雷达Title 数据
     */
    private void getRadarTitleDesc() {
        HashMap<String, String> map = new HashMap<>(4);
        map.put(Constants.USER_ID, UserUtil.getUserId());

        //temp
        //        map.put(Constants.USER_ID, "BC20181029101458A0pT");
        //        map.put(Constants.TOKEN, "00d9b360f856435685c1187bbfd826041543927657615");
        mNetPresenter.getObject(mContext, NetConstants.URL.GET_RADAR_DESC, map, RadarTitleBean.class, MSG_RADAR_TITLE);
    }

    /**
     * 获取雷达图分析结果数据
     */
    private void getRadarAnalysisData() {
        HashMap<String, String> map = new HashMap<>(4);
        map.put(Constants.PHOTO_NO, UserUtil.getPhotoNo());

        //temp
        //        map.put(Constants.PHOTO_NO, "CN20181205191704QETz");
        //        map.put(Constants.TOKEN, "00d9b360f856435685c1187bbfd826041543927657615");
        mNetPresenter.getObject(mContext, NetConstants.URL.GET_FACE_RESULT, map, RadarResultBean.class, MSG_FACE_RESULT);
    }


    private static final int MSG_RADAR_TITLE = 0X001;
    private static final int MSG_FACE_RESULT = 0X002;


    /**
     * 网络加载前
     *
     * @param msgCode 消息识别码 用来判断是哪次网络请求
     */
    @Override
    public void onLoadPre(int msgCode) {
    }

    /**
     * 网络加载成功
     */
    @Override
    public void onLoadSuccess(Object result, int msgCode) {
        if (msgCode == MSG_FACE_RESULT) {
            //设置雷达图结果数据
            setRadarResult(result);
        } else if (msgCode == MSG_RADAR_TITLE) {
            //设置雷达图标题数据
            setRadarTitle(result);
            //获取到标题之后再获取雷达图数据
            getRadarAnalysisData();
        }
    }


    /**
     * 网络加载失败
     */
    @Override
    public void onLoadFail(int errorCode, String errorMsg, int msgCode) {
        if (msgCode == MSG_FACE_RESULT) {
            toast(errorCode + errorMsg);
        } else if (msgCode == MSG_RADAR_TITLE) {
            toast(errorCode + errorMsg + "Title获取失败");
        }

    }


    private static final int WOMAN = 2;
    private static final int MAN = 1;


    /**
     * 设置雷达图的标题
     *
     * @param result 返回的Result Bean
     */
    private void setRadarTitle(Object result) {
        RadarTitleBean titleBean = (RadarTitleBean) result;
        mTitleList = Optional.ofNullable(titleBean)
                .flatMap(b -> Optional.ofNullable(b.getList()))
                .orElse(new ArrayList<>());

        if (mTitleList.size() > 0) {
            if (UserUtil.getGender() == WOMAN) {
                mRadarViewWoman.setRadarTitle(mTitleList);
            } else if (UserUtil.getGender() == MAN) {
                mRadarViewMan.setRadarTitle(mTitleList);
            }
        } else {
            toast("Title获取失败~");
        }
    }

    private int num = 0;
    //雅风格处于Title中的position
    private int currentIndex = 0;

    /**
     * 判断雷达图数据是否分析完成
     *
     * @param result 返回的Result Bean
     */
    private void setRadarResult(Object result) {
        mRadarResultBean = (RadarResultBean) result;
        if (mRadarResultBean != null) {
            // 正在分析或正确分析完成
            if (mRadarResultBean.getIfAll() == 1 || mRadarResultBean.getIfAll() == 2) {
                setDataToRadar(mRadarResultBean);
            }

            if (mRadarResultBean.getIfAll() != 2 && mRadarResultBean.getIfAll() != 3) {
                if (num >= 20) {
                    toast("获取数据失败~");
                    return;
                }
                num++;
                getRadarAnalysisData();
            }
        }
    }

    private void setDataToRadar(RadarResultBean result) {
        //关键词
        if (!TextUtils.isEmpty(result.getStyleLabels())) {
            String[] labels = result.getStyleLabels().split(",");
            mSpreadTV.setTvList(Arrays.asList(labels));
        }

        //获取雅风格对应的position
        int secondStyleId = result.getSecondStyleId();
        for (int i = 0; i < mTitleList.size(); i++) {
            int styleId = mTitleList.get(i).getStyleId();
            if (secondStyleId == styleId) {
                currentIndex = i;
            }
        }

        //设置雷达图数值 男女Radar  1男 2女
        try {
            if (result.getStyleScores() != null && result.getStyleScores().length > 0) {
                float[] scoreArray = new float[result.getStyleScores().length];
                for (int i = 0; i < result.getStyleScores().length; i++) {
                    scoreArray[i] = Float.parseFloat(result.getStyleScores()[i]);
                }
                mOptimizedStyleScores = getOptimizedStyleScores(scoreArray);

                if (result.getStyleScores().length == 8) {
                    mRadarViewMan.setVisibility(View.GONE);
                    mRadarViewWoman.setVisibility(View.VISIBLE);
                    mRadarViewWoman.setPercentValues(mOptimizedStyleScores, currentIndex);
                } else {
                    mRadarViewWoman.setVisibility(View.GONE);
                    mRadarViewMan.setVisibility(View.VISIBLE);
                    mRadarViewMan.setPercentValues(mOptimizedStyleScores, currentIndex);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将返回的雷达图数值按一定比例重新计算  避免雷达图区域太小
     *
     * @param styleScoreArray 雷达图的数值  男性5个 女性8个
     * @return 返回重新计算过后的雷达图数值
     */
    private float[] getOptimizedStyleScores(float[] styleScoreArray) {
        if (styleScoreArray == null || styleScoreArray.length == 0) {
            return null;
        }
        float[] mNewStyleScoreArray = new float[8];
        float[] mCocyScoreArray = new float[styleScoreArray.length];
        System.arraycopy(styleScoreArray, 0, mCocyScoreArray, 0, styleScoreArray.length);
        Arrays.sort(mCocyScoreArray);

        if (styleScoreArray[mCocyScoreArray.length - 1] < 75) {
            float factor = 75 / mCocyScoreArray[mCocyScoreArray.length - 1];
            for (int i = 0; i < styleScoreArray.length; i++) {
                mNewStyleScoreArray[i] = styleScoreArray[i] * factor / 100f;
            }
        } else {
            for (int i = 0; i < styleScoreArray.length; i++) {
                mNewStyleScoreArray[i] = styleScoreArray[i] / 100f;
            }
        }
        return mNewStyleScoreArray;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mNetPresenter != null) {
            mNetPresenter.onDestroy();
        }
    }

//    public void hideRadar() {
//        if (mRadarResultBean == null) {
//            return;
//        }
//
//        if (UserUtil.getGender() == 2) {
//            mRadarViewWoman.setVisibility(View.GONE);
//        } else {
//            mRadarViewMan.setVisibility(View.GONE);
//        }
//    }

//    public void showRadar() {
//        if (mRadarResultBean == null) {
//            return;
//        }
//        if (UserUtil.getGender() == 2) {
//            mRadarViewWoman.setVisibility(View.VISIBLE);
//        } else {
//            mRadarViewMan.setVisibility(View.VISIBLE);
//        }
//    }


//    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//        if (hidden) {
//            hideRadar();
//        } else {
//            showRadar();
//        }
//    }
}
